<?php

/**
*
* @package
* @version $Id:$
* @copyright
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
include($phpbb_root_path . 'includes/functions_facebook.' . $phpEx);
include($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
	
global $auth, $config, $user, $db, $phpbb_root_path, $phpEx, $template;

$user->session_begin();
$auth->acl($user->data);
$user->setup(array('ucp', 'common'));

$captcha =& phpbb_captcha_factory::get_instance($config['captcha_plugin']);
$captcha->init(CONFIRM_REG);

$facebook = new Facebook(array(
  'appId' => $config['fb_appid'],
  'secret' => $config['fb_secret'],
  'cookie' => true,
));

$session = $facebook->getSession();

$fbuser = null;

if ($session) {
  try {
    $uid = $facebook->getUser();
    $fbuser = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

if(!$user->data['is_registered']) {

if($fbuser) {

$server_url = generate_board_url();

$check_user_sql = "SELECT username, user_email FROM " . USERS_TABLE . " WHERE username = '{$db->sql_escape($fbuser['name'])}'";
$result_user = $db->sql_query($check_user_sql);
$check_user = $db->sql_fetchrow($result_user);
$db->sql_freeresult($result_user);

$form_key = 'fbconnect_form';
add_form_key($form_key);

$errors = array();

if($fbuser['name'] == $check_user['username']) {

$template->assign_vars(array(
   'USE_USERNAME'         => true,
));

$errors['USERNAME_TAKEN'] = sprintf($user->lang['FB_USERNAME_TAKEN'], $fbuser['name']);

}

if($fbuser['email'] == $check_user['user_email']) {

$template->assign_vars(array(
   'USE_EMAIL'         => true,
));

$errors['EMAIL_TAKEN'] = sprintf($user->lang['FB_EMAIL_TAKEN'], $fbuser['email']);

}

if ($config['enable_confirm'])
{
 $template->assign_vars(array(
  'CAPTCHA_TEMPLATE'		=> $captcha->get_template(),
 ));
}

$fbsubmit = (isset($_POST['fbsubmit'])) ? true : false;
if($fbsubmit) {

$fbdata = array(
   'user_username'			=> ($fbuser['name'] == $check_user['username'] || utf8_normalize_nfc(request_var('user_username', '', true))) ? utf8_normalize_nfc(request_var('user_username', '', true)) : $fbuser['name'],
   'password'		=> request_var('user_password', '', true),
   'password_confirm'		=> request_var('user_password_confirm', '', true),
   'email'				=> ($fbuser['email'] == $check_user['user_email'] || request_var('user_email', '')) ? strtolower(request_var('user_email', '')) : $fbuser['email'],
);

$errors = validate_data($fbdata, array(
   'user_username'			=> array(
		array('string', false, $config['min_name_chars'], $config['max_name_chars']),
		array('username', '')),
	 'password'		=> array(
		array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
		array('password')),
		'password_confirm'		=> array(
		array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
		array('password')),
	 'email'				=> array(
		array('string', false, 6, 60),
	  array('email')),
));

$errors = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $errors);

$is_valid = $captcha->validate($fbdata);
if($is_valid  !== false)
{
 $errors[] = $user->lang['FB_CAPTCHA_WRONG'];
}

if (!check_form_key($form_key))
{
 $errors[] = $user->lang['FORM_INVALID'];
}

if ($config['enable_confirm'] && isset($captcha))
{
 $captcha->reset();
}

if($config['max_reg_attempts'] && $captcha->get_attempt_count() > $config['max_reg_attempts'])
 {
  $errors[] = $user->lang['TOO_MANY_REGISTERS'];
 }

if(request_var("user_password", "", true) != request_var("user_password_confirm", "", true))
 {
  $errors[] = $user->lang['FB_PASSWORDS_DONT_MATCH'];
 }

if(sizeof($errors)) {

$template->assign_vars(array(
   'USE_USERNAME'         => ($fbuser['name'] == $check_user['username']) ? true : false,
   'USE_EMAIL'         => ($fbuser['email'] == $check_user['user_email']) ? true : false,
));

}

if($config['check_dnsbl'])
{
 if (($dnsbl = $user->check_dnsbl('register')) !== false)
 {
  $errors[] = sprintf($user->lang['IP_BLACKLISTED'], $user->ip, $dnsbl[1]);
 }
}

if(!sizeof($errors)) {

// Are user_location and user_website here
$fbuser_location = ($fbuser['location']['name']) ? array('user_from' => $fbuser['location']['name']) : array();
$fbuser_website = ($fbuser['website']) ? array('user_website' => $fbuser['website']) : array();

// List user_birthday
list($day, $month, $year) = explode("/", $fbuser['birthday']);

$group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED';

$sql_group = 'SELECT group_id
 FROM ' . GROUPS_TABLE . "
  WHERE group_name = '" . $db->sql_escape($group_name) . "'
   AND group_type = " . GROUP_SPECIAL;
$result_group = $db->sql_query($sql_group);
$row_group = $db->sql_fetchrow($result_group);
$db->sql_freeresult($result_group);

if(!$row_group)
{
trigger_error('NO_GROUP');
}

$group_id = $row_group['group_id'];

if (($coppa ||
 $config['require_activation'] == USER_ACTIVATION_SELF ||
 $config['require_activation'] == USER_ACTIVATION_ADMIN) && $config['email_enable'])
{
 $user_actkey = gen_rand_string(10);
 $key_len = 54 - (strlen($server_url));
 $key_len = ($key_len < 6) ? 6 : $key_len;
 $user_actkey = substr($user_actkey, 0, $key_len);

 $user_type = USER_INACTIVE;
 $user_inactive_reason = INACTIVE_REGISTER;
 $user_inactive_time = time();
}
 else
{
 $user_type = USER_NORMAL;
 $user_actkey = '';
 $user_inactive_reason = 0;
 $user_inactive_time = 0;
}

$user_row = array(
    'username'              => $fbdata['user_username'],
    'user_password'         => phpbb_hash($fbdata['password']),
    'user_email'            => $fbdata['email'],
    'group_id'              => (int) $group_id,
    'user_timezone'         => (float) ($fbuser['timezone']) ? $fbuser['timezone'] : date('Z') / 3600,
    'user_lang'             => basename($user->lang_name),
    'user_type'             => $user_type,
    'user_ip'               => $user->ip,
    'user_regdate'          => time(),
    'user_birthday'         => sprintf('%2d-%2d-%4d', $day, $month, $year),
    'user_avatar'           => "https://graph.facebook.com/{$uid}/picture",
    'user_avatar_type'      => 2,
    'user_avatar_width'     => $config['fb_pic_width'],
    'user_avatar_height'    => $config['fb_pic_height'],
    'user_inactive_reason'	=> $user_inactive_reason,
		'user_inactive_time'	=> $user_inactive_time,
		'user_actkey'			=> $user_actkey,
);

if ($config['new_member_post_limit'])
{
 $user_row['user_new'] = 1;
}

// If array merge with user_row
$user_row = (sizeof($fbuser_location)) ? array_merge($user_row, $fbuser_location) : $user_row;
$user_row = (sizeof($fbuser_website)) ? array_merge($user_row, $fbuser_website) : $user_row;

// Register the user!
$user_add = user_add($user_row);

// As said in ucp_register.php, this should not be shown.
if ($user_add === false)
{
 trigger_error('NO_USER', E_USER_ERROR);
}

				if ($coppa && $config['email_enable'])
				{
					$message = $user->lang['ACCOUNT_COPPA'];
					$email_template = 'coppa_welcome_inactive';
				}
				else if ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable'])
				{
					$message = $user->lang['ACCOUNT_INACTIVE'];
					$email_template = 'user_welcome_inactive';
				}
				else if ($config['require_activation'] == USER_ACTIVATION_ADMIN && $config['email_enable'])
				{
					$message = $user->lang['ACCOUNT_INACTIVE_ADMIN'];
					$email_template = 'admin_welcome_inactive';
				}
				else
				{
					$message = $user->lang['ACCOUNT_ADDED'];
					$email_template = 'user_welcome';
				}

				if ($config['email_enable'])
				{
					include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);

					$messenger = new messenger(false);

					$messenger->template($email_template, basename($user->lang_name));

					$messenger->to($fbdata['email'], $fbdata['user_username']);

					$messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
					$messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
					$messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
					$messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);

					$messenger->assign_vars(array(
						'WELCOME_MSG'	=> htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])),
						'USERNAME'		=> htmlspecialchars_decode($fbdata['user_username']),
						'PASSWORD'		=> htmlspecialchars_decode($fbdata['password']),
						'U_ACTIVATE'	=> "$server_url/ucp.$phpEx?mode=activate&u=$user_add&k=$user_actkey")
					);

					if ($coppa)
					{
						$messenger->assign_vars(array(
							'FAX_INFO'		=> $config['coppa_fax'],
							'MAIL_INFO'		=> $config['coppa_mail'],
							'EMAIL_ADDRESS'	=> $fbdata['email'])
						);
					}

					$messenger->send(NOTIFY_EMAIL);

					if ($config['require_activation'] == USER_ACTIVATION_ADMIN)
					{
						// Grab an array of user_id's with a_user permissions ... these users can activate a user
						$admin_ary = $auth->acl_get_list(false, 'a_user', false);
						$admin_ary = (!empty($admin_ary[0]['a_user'])) ? $admin_ary[0]['a_user'] : array();

						// Also include founders
						$where_sql = ' WHERE user_type = ' . USER_FOUNDER;

						if (sizeof($admin_ary))
						{
							$where_sql .= ' OR ' . $db->sql_in_set('user_id', $admin_ary);
						}

						$sql = 'SELECT user_id, username, user_email, user_lang, user_jabber, user_notify_type
							FROM ' . USERS_TABLE . ' ' .
							$where_sql;
						$result = $db->sql_query($sql);

						while ($row = $db->sql_fetchrow($result))
						{
							$messenger->template('admin_activate', $row['user_lang']);
							$messenger->to($row['user_email'], $row['username']);
							$messenger->im($row['user_jabber'], $row['username']);

							$messenger->assign_vars(array(
								'USERNAME'			=> htmlspecialchars_decode($fbdata['user_username']),
								'U_USER_DETAILS'	=> "$server_url/memberlist.$phpEx?mode=viewprofile&u=$user_add",
								'U_ACTIVATE'		=> "$server_url/ucp.$phpEx?mode=activate&u=$user_add&k=$user_actkey")
							);

							$messenger->send($row['user_notify_type']);
						}
						$db->sql_freeresult($result);
					}
				}

// Some default messages
//$message = $message . '<br /><br />' . sprintf($user->lang['RETURN_INDEX'], '<a href="' . append_sid("{$phpbb_root_path}index.$phpEx") . '">', '</a>');
//trigger_error($message);

switch ($config['require_activation'])
{
 case USER_ACTIVATION_SELF:
  // Say what to do
  trigger_error($user->lang['UCP_EMAIL_ACTIVATE']);
 break;
 
 case USER_ACTIVATION_ADMIN:
  // Say what to do
  trigger_error($user->lang['UCP_ADMIN_ACTIVATE']);
 break;
 
 default:
 $password_login = request_var("user_password", "", true);
 // Login the new user
 $auth->login(utf8_normalize_nfc((request_var("user_username", "", true))) ? utf8_normalize_nfc(request_var("user_username", "", true)) : $fbuser['name'], $password_login);
 // No need of this anymore
 unset($password_login);
 // Go to index
 redirect("{$phpbb_root_path}index.$phpEx");
 break;
 
}

}

  }
 }
} else {
// Back to index
redirect("{$phpbb_root_path}index.$phpEx");
}

// FB details
$template->assign_vars(array(
   'FB_APPID'         => $facebook->getAppId(),
   'FB_SESSION'         => json_encode($session),
   'FB_USER'         => $fbuser,
));

// Is hidden
$s_hidden_fields = array(
   'user_name_saved'   => request_var('user_username', '', true),
   'user_email_saved'   => request_var('user_email', '', true),
);

if($config['coppa_enable'])
{
   $s_hidden_fields['coppa'] = $coppa;
}

// Roll if errors
$template->assign_vars(array(
   'S_HIDDEN_FIELDS'   => build_hidden_fields($captcha->get_hidden_fields()),
   'ERRORS'				=> (sizeof($errors)) ? implode('<br />', $errors) : '',
));

$template->assign_vars(array(
   'USERNAME_EXPLAIN'         => sprintf($user->lang['FB_USERNAME_EXPLAIN'], $config['min_name_chars'], $config['max_name_chars']),
   'REGISTER_EXPLAIN'         => sprintf($user->lang['FB_REGISTER_EXPLAIN'], $config['sitename']),
   'FB_USERNAME'         => request_var('user_username', ''),
   'FB_EMAIL'         => request_var('user_email', ''),
));

page_header($user->lang['FB_TITLE']);

$template->set_filenames(array(
   'body'         => 'connect.html',
));

page_footer();

?>